﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Relocation.Data;
using System.Data.Objects;
using Relocation.Base;
using Relocation.Com;
using Relocation.Base.UI;
using Relocation.Forms.ListBase;

 
namespace Relocation
{
	public partial class UserList : UserListBase
	{
		public UserList():base()
		{
			Initialize();
		}

		public UserList(Session session):base(session)
		{	
			Initialize();
		}

		public void Initialize()
		{
			InitializeComponent();
			InitalizeRole();
			this.ObjectQuery = this.Session.DataModel.User;
		}

		private void InitalizeRole()
		{
			ControlTag tag = new ControlTag(new RoleInfo(Session.KEY_ROLE_ADMIN));
			this.ButtonAdd.Tag = tag;
			this.ButtonDel.Tag = tag;
			this.ButtonEdit.Tag = tag;
		}

		private void add_Click(object sender, EventArgs e)
		{
			try
			{
				using (UserWindow userWin = new UserWindow(Session))
				{					
					userWin.Text = "创建用户";
					if (userWin.ShowDialog().IsOK())
					{
						this.Refresh();
					}
				}
			} catch (Exception ex)
			{
				Log.Error(ex.Message);
				MyMessagebox.Error("操作失败！");
			}
		}

		private void alter_Click(object sender, EventArgs e)
		{
			try
			{
				User user = this.GetSelectEntity();
				if(user==null)
					return;
				using(UserWindow userWin = new UserWindow(Session, user))
				{
					userWin.Text = "修改用户";
					if (userWin.ShowDialog().IsOK())
						this.Refresh();
				}
			} catch (Exception ex)
			{
				Log.Error(ex.Message);
				MyMessagebox.Error("操作失败！");
			}
		}

		private void delete_Click(object sender, EventArgs e)
		{
			try
			{
				User user = this.GetSelectEntity();
				if (user == null)
					return;
				this.DeleteEntity(user);
				this.Refresh();
			} catch (Exception ex)
			{
				Log.Error(ex.Message);
				MyMessagebox.Error("操作失败！");
			}
		}

		public override void Refresh()
		{
			try
			{
				base.Refresh();
				this.Reload();
			} catch (Exception ex)
			{				
				Log.Error(ex.GetInnerExceptionMessage());
				System.Diagnostics.Debug.WriteLine(ex);
			}
		}

		private void userDataview_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
		{
			if (e.ColumnIndex == 4)
			{
				if (e.Value.ToString().Equals("admin"))
				{
					e.Value = "管理员";
				} else if (e.Value.ToString().Equals("operator"))
				{
					e.Value = "操作员";
				} else
				{
					e.Value = "普通用户";
				}
			} else if (e.ColumnIndex == 2)
			{
				e.Value = "******";
			}
		}
	}
}
